import React, { useState, useEffect } from 'react';
import { useLocation } from 'react-router-dom';
import ModelVersionTimeline from '../components/ModelVersionTimeline';
import { Spin, Alert } from 'antd';

const ModelVersionTimelinePage: React.FC = () => {
  const location = useLocation();
  const [loading, setLoading] = useState(false);
  const [timelineData, setTimelineData] = useState<any>(null);
  const [error, setError] = useState<string | null>(null);
  
  // 从URL参数中获取模型ID
  const searchParams = new URLSearchParams(location.search);
  const modelId = searchParams.get('modelId');
  
  useEffect(() => {
    if (!modelId) return;
    
    const fetchTimelineData = async () => {
      setLoading(true);
      setError(null);
      
      try {
        const apiUrl = `/training_model_modelview/api/action/view_version_timeline/${modelId}`;
        const response = await fetch(apiUrl, {
          method: 'GET',
          headers: {
            'Content-Type': 'application/json',
          },
          credentials: 'same-origin'
        });

        if (!response.ok) {
          throw new Error(`HTTP ${response.status}: ${response.statusText}`);
        }

        const result = await response.json();
        
        if (result.status === 0 || result.data) {
          setTimelineData(result.data);
        } else {
          throw new Error(result.message || '获取数据失败');
        }
      } catch (err) {
        setError(err instanceof Error ? err.message : '未知错误');
        console.error('获取版本时间线数据失败:', err);
      } finally {
        setLoading(false);
      }
    };
    
    fetchTimelineData();
  }, [modelId]);

  if (!modelId) {
    return (
      <div style={{ padding: '50px', textAlign: 'center' }}>
        <h3>缺少模型ID参数</h3>
        <p>请提供有效的模型ID参数</p>
      </div>
    );
  }
  
  if (error) {
    return (
      <div style={{ padding: '20px' }}>
        <Alert
          message="获取版本时间线失败"
          description={error}
          type="error"
          showIcon
        />
      </div>
    );
  }

  return (
    <div style={{ padding: '20px' }}>
      <ModelVersionTimeline 
        data={timelineData}
        loading={loading}
        width={window.innerWidth - 80}
        height={window.innerHeight - 100}
      />
    </div>
  );
};

export default ModelVersionTimelinePage; 